package com.aegean.MonitorExamSYS.monitor.business.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aegean.MonitorExamSYS.monitor.business.MonitorBusiness;
import com.aegean.MonitorExamSYS.monitor.component.ExamPosition;
import com.aegean.MonitorExamSYS.monitor.component.ExamineeState;
import com.aegean.MonitorExamSYS.monitor.dao.MonitorDao;
import com.aegean.MonitorExamSYS.tools.MyTools;
import com.aegean.MonitorExaxSYS.model.BigType;
import com.aegean.MonitorExaxSYS.model.ConductionValue;
import com.aegean.MonitorExaxSYS.model.MonitorValue;
import com.aegean.MonitorExaxSYS.model.SmallType;
import com.aegean.MonitorExaxSYS.model.component.Photo;

@Service
@Transactional
public class MonitorBusinessImpl implements MonitorBusiness {
	@Resource
	MonitorDao dao;

	public List<BigType> showBigsList() {
		// TODO Auto-generated method stub
		return dao.showBigsList();
	}

	@Override
	public List<SmallType> showSmallsList(int big_Id) {
		// TODO Auto-generated method stub
		return dao.showSmallsList(big_Id);
	}

	@Override
	public MonitorValue insertMonitor(MonitorValue one, int big_Id, int unit_Id) {
		// TODO Auto-generated method stub
		one.setMonitor_State(0);
		return dao.insertMonitor(one, big_Id, unit_Id);
	}

	@Override
	public List<ConductionValue> showUnitList() {
		// TODO Auto-generated method stub
		List<ConductionValue> units = dao.showUnitList();
		return units;
	}

	@Override
	public MonitorValue loginMonitor(MonitorValue one, int unit_Id) {
		// TODO Auto-generated method stub
		return dao.loginMonitor(one, unit_Id);
	}

	@Override
	public Blob showPhoto(int Customer_Id) {
		// TODO Auto-generated method stub
		return dao.showPhoto(Customer_Id);
	}

	@Override
	public MonitorValue updateMonitor(int Customer_Id, MonitorValue one,
			Photo photo) {
		// TODO Auto-generated method stub
		return dao.updateMonitor(Customer_Id, one, photo);
	}

	@Override
	public MonitorValue updateMonitorPwd(int Customer_Id, String newPwd) {
		// TODO Auto-generated method stub
		return dao.updateMonitorPwd(Customer_Id, newPwd);
	}

	@Override
	public List<ExamPosition> showMonitorExams(int monitor_Id, int limit,
			int start) {
		// TODO Auto-generated method stub
		return dao.showMonitorExams(monitor_Id, limit, start);
	}

	@Override
	public List<com.aegean.MonitorExamSYS.monitor.component.MonitorValue> showMonitorValues(
			int ep_Id) {
		return dao.showMonitorValues(ep_Id);
	}

	@Override
	public int countOfExaminees(int ep_Id) {
		// TODO Auto-generated method stub
		return dao.countOfExaminees(ep_Id);
	}

	@Override
	public int showMonitorExamsCount(int monitor_Id) {
		// TODO Auto-generated method stub
		return dao.showMonitorExamsCount(monitor_Id);
	}

	@Override
	public List<ExamineeState> showExamineeOnPosition(int position_Id,
			String root, String position) {
		// TODO Auto-generated method stub
		List<ExamineeState> results = dao.showExamineeOnPosition(position_Id);
		otherThread thread = new otherThread(position_Id, results.size(), root,
				position);
		thread.start();
		return results;
	}

	class otherThread extends Thread {
		private int position_Id;
		private int total;
		private String root;
		private String position;

		public otherThread(int position_Id, int total, String root,
				String position) {
			this.position_Id = position_Id;
			this.total = total;
			this.root = root;
			this.position = position;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<Photo> photos = dao.downLoadPhotos(this.position_Id);
			for (Photo photo : photos) {
				File file_root = new File(root);
				File file_position = new File(position);
				if (!file_root.exists()) {
					file_root.mkdir();
				}
				if (!file_position.exists()) {
					file_position.mkdir();
				}
				if (file_position.listFiles().length == total) {
					break;
				} else {
					File file_Photo = new File(position,
							photo.getPhoto_userId() + "_"
									+ photo.getPhoto_Name());
					try {
						FileOutputStream out = new FileOutputStream(file_Photo);
						InputStream in = photo.getPhoto().getBinaryStream();
						byte[] buffer = new byte[1024];
						int length;
						while ((length = in.read(buffer)) != -1) {
							out.write(buffer, 0, length);
						}
						in.close();
						out.close();
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}

				}
			}
		}
	}

	@Override
	public List<com.aegean.MonitorExamSYS.monitor.component.MonitorValue> showMonitorOnPosition(
			int position_Id) {
		// TODO Auto-generated method stub
		return dao.showMonitorOnPosition(position_Id);
	}

	@Override
	public InputStream downExelForMonitor(
			String exam_Name,
			String position_Name,
			String monitor_Identiy,
			String startTime,
			String endTime,
			int personCount,
			String position_Identity,
			List<com.aegean.MonitorExamSYS.monitor.component.MonitorValue> monitors,
			String monitor_RealName) {
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			HSSFWorkbook work = new HSSFWorkbook();
			Sheet sheet = work.createSheet("监考安排表");
			Row rowTile = sheet.createRow(0);
			HSSFFont fontTile = work.createFont();
			fontTile.setFontHeightInPoints((short) 20); // 字体高度
			fontTile.setColor(HSSFFont.COLOR_RED); // 字体颜色
			fontTile.setFontName("宋体 "); // 字体
			fontTile.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 宽度
			fontTile.setItalic(false); // 是否使用斜体
			rowTile.setHeight((short) 700);// 设置标题行的高度
			HSSFCellStyle cellStyleTile = work.createCellStyle();
			cellStyleTile.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
			cellStyleTile.setFont(fontTile);
			for (int i = 0; i < 12; i++) {
				Cell cell = rowTile.createCell(i);
				cell.setCellStyle(cellStyleTile);
				sheet.setColumnWidth(i, 3500);
			}
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 8));
			rowTile.getCell(3).setCellValue("监考人员安排信息表");
			Row[] rows = new Row[11];
			for (int i = 1; i <= 11; i++) {
				rows[i - 1] = sheet.createRow(i);
				rows[i - 1].setHeight((short) 500);
				for (int j = 0; j < 12; j++) {
					createCell(work, rows[i - 1], j, HSSFCellStyle.ALIGN_LEFT,
							HSSFCellStyle.VERTICAL_JUSTIFY, null);
					if (i > 2) {
						sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 8));
					}
				}
			}
			rows[0].getCell(8).setCellValue("监考人员");
			rows[0].getCell(9).setCellValue(monitor_RealName);
			rows[1].getCell(8).setCellValue("创建时间");
			rows[1].getCell(9).setCellValue(MyTools.toDateString(new Date()));
			String[] tiles = { "考场项目：", "开始时间：", "结束时间：", "考场地址：", "考场资格：",
					"监考资格：", "监考人员：", "监考人数：" };
			String[] contents = {
					exam_Name,
					startTime,
					endTime,
					position_Name,
					position_Identity,
					monitor_Identiy,
					monitors.get(0).getUser_RealName() + "  ,  "
							+ monitors.get(1).getUser_RealName(),
					String.valueOf(personCount) };
			for (int i = 1; i < 9; i++) {
				rows[i + 1].getCell(2).setCellValue(tiles[i - 1]);
				rows[i + 1].getCell(3).setCellValue(contents[i - 1]);
			}
			work.write(os);
			byte[] content = os.toByteArray();
			InputStream in = new ByteArrayInputStream(content);
			return in;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static void createCell(HSSFWorkbook wb, Row row, int col,
			short align, short vlign, String val) {
		Cell cell = row.createCell(col);
		cell.setCellValue(val);
		HSSFCellStyle cellstyle = wb.createCellStyle();
		cellstyle.setAlignment(align);
		cellstyle.setVerticalAlignment(vlign);
		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 12); // 字体高度
		cellstyle.setFont(font);
		cell.setCellStyle(cellstyle);
	}

	@Override
	public InputStream downExcelPosition(int position_Id, String root,
			String exam_Name, String startTime, String endTime,
			String position_Name) {
		// TODO Auto-generated method stub
		List<ExamineeState> examinees = dao.showExamineeOnPosition(position_Id);
		List<com.aegean.MonitorExamSYS.monitor.component.MonitorValue> monitors = dao
				.showMonitorOnPosition(position_Id);
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			HSSFWorkbook work = new HSSFWorkbook();
			Sheet sheet = work.createSheet("考场安排信息表");
			CreationHelper helper = work.getCreationHelper();
			Row rowTile = sheet.createRow(0);
			HSSFFont fontTile = work.createFont();
			fontTile.setFontHeightInPoints((short) 20); // 字体高度
			fontTile.setColor(HSSFFont.COLOR_RED); // 字体颜色
			fontTile.setFontName("宋体 "); // 字体
			fontTile.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 宽度
			fontTile.setItalic(false); // 是否使用斜体
			rowTile.setHeight((short) 700);// 设置标题行的高度
			HSSFCellStyle cellStyleTile = work.createCellStyle();
			cellStyleTile.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
			cellStyleTile.setFont(fontTile);
			for (int i = 0; i < 12; i++) {
				Cell cell = rowTile.createCell(i);
				cell.setCellStyle(cellStyleTile);
				if (i == 3 || i == 7 || i == 8) {
					sheet.setColumnWidth(i, 5000);
				} else if (i == 4) {
					sheet.setColumnWidth(i, 6500);
				} else {
					sheet.setColumnWidth(i, 3500);
				}

			}
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 8));
			rowTile.getCell(3).setCellValue("考场安排信息表");
			Row[] tags = new Row[2];
			for (int i = 1; i <= 2; i++) {
				tags[i - 1] = sheet.createRow(i);
				tags[i - 1].setHeight((short) 500);
				for (int j = 0; j < 12; j++) {
					createCell(work, tags[i - 1], j, HSSFCellStyle.ALIGN_LEFT,
							HSSFCellStyle.VERTICAL_BOTTOM, null);
				}
			}
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 4));
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 4));
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 6, 7));
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 6, 7));
			tags[0].getCell(0).setCellValue("考试内容：");
			tags[0].getCell(1).setCellValue(exam_Name);
			tags[0].getCell(5).setCellValue("监考人员：");
			tags[0].getCell(6).setCellValue(
					monitors.get(0).getUser_RealName() + "  ，  "
							+ monitors.get(1).getUser_RealName());
			tags[0].getCell(8).setCellValue("考生人数：");
			tags[0].getCell(9).setCellValue(String.valueOf(examinees.size()));
			tags[1].getCell(0).setCellValue("考试时间：");
			tags[1].getCell(1).setCellValue(startTime + "~" + endTime);
			tags[1].getCell(5).setCellValue("考试地址：");
			tags[1].getCell(6).setCellValue(position_Name);
			tags[1].getCell(8).setCellValue("创建时间：");
			tags[1].getCell(9).setCellValue(MyTools.toDateString(new Date()));
			String[] tiles = { "序号", "考生姓名", "性别", "准考证号", "身份证号", "年龄", "状态",
					"联系方式", "照片", "备注" };
			Row rowTitle = sheet.createRow(3);
			rowTitle.setHeight((short) 500);
			for (int i = 0; i < tiles.length; i++) {
				createCell(work, rowTitle, i, HSSFCellStyle.ALIGN_CENTER,
						HSSFCellStyle.VERTICAL_CENTER, tiles[i]);
			}
			Row[] rows = new Row[examinees.size()];
			for (int i = 4; i < rows.length + 4; i++) {
				rows[i - 4] = sheet.createRow(i);
				rows[i - 4].setHeight((short) 2000);
				for (int j = 0; j < 10; j++) {
					switch (j) {
					case 0:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								String.valueOf(i - 3));
						break;
					case 1:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								examinees.get(i - 4).getUser_RealName());
						break;
					case 2:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								String.valueOf(examinees.get(i - 4)
										.getUser_Sex()));
						break;
					case 3:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								examinees.get(i - 4).getExam_Identity());
						break;
					case 4:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								examinees.get(i - 4)
										.getExamineeValue_IdentityCard());
						break;
					case 5:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								String.valueOf(examinees.get(i - 4)
										.getExamineeValue_Age()));
						break;
					case 6:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER, "正常");
						break;
					case 7:
						createCell(work, rows[i - 4], j,
								HSSFCellStyle.ALIGN_CENTER,
								HSSFCellStyle.VERTICAL_CENTER,
								examinees.get(i - 4).getExamineeValue_Phone());
						break;
					case 8:
						File file = new File(root
								+ "/"
								+ examinees.get(i - 4).getUser_Id()
								+ "_"
								+ examinees.get(i - 4).getUser_Photo()
										.getPhoto_Name());
						InputStream is = new FileInputStream(file);
					    byte[] bytes = IOUtils.toByteArray(is);
					    int pictureIdx =work.addPicture(bytes,work.PICTURE_TYPE_JPEG);
					    Drawing drawing = sheet.createDrawingPatriarch();
					    ClientAnchor anchor =helper.createClientAnchor();
					    anchor.setCol1(8);
					    anchor.setRow1(i);
					    anchor.setCol2(9);
					    anchor.setRow2(i+1);
					    Picture pict = drawing.createPicture(anchor, pictureIdx);
					    is.close();
						break;
					}
				}
			}
			work.write(os);
			byte[] content = os.toByteArray();
			InputStream in = new ByteArrayInputStream(content);
			return in;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
